<script lang="ts" setup>
import { ref, reactive, watch, watchEffect, onMounted, onUnmounted } from "vue";

import { objectToQueryParams } from "../../../utils/objectToQuery";
import {
  formatTableCol,
  getColWidth,
  setColWidth,
  setLastWidth,
} from "./FormatData";
import { isDate, formatDate } from "../../../utils/formatDate";
import * as BasicApi from "../../../api/search";

import { useMessage } from "../../../hooks/useMessage";
const message = useMessage();

import EditModal from "./EditModal.vue";
import BreakdownModal from "./BreakdownModal.vue";
import eventBus from "../../../libs/eventBus";
// import DetailModal from './DetailModal.vue'
// import { checkTagExists } from '@/utils/checkTagExists'

// const props = defineProps(['partParams', 'compName'])
const props = defineProps({
  partParams: {
    type: Object,
  },
  compName: {
    type: String,
  },
  tableInfo: {
    type: Object,
  },
});
const loading = ref(false); // 列表的加载中
const total = ref(0); // 列表的总页数

const list = ref<any[]>([]); // 列表的数据
const column = ref<any[]>([]); // 列表的表头

const headList = ref<any[]>([]); // 列表的数据

const selectShow = ref(); //列表行多选框
const operList = ref<any[]>([]);

const queryParams = reactive({
  type: "",
  value: "",
  keyType: "",
  list: [],
  groupName: "",
  jobType: "",
});

watch(
  () => props.partParams,
  (val: any) => {
    Object.assign(queryParams, val);
    queryParams.groupName && getList();
  }
);

/** 查询岗位列表 */
const getList = async () => {
  loading.value = true;
  try {
    const post = {
      ...queryParams,
    };
    const inputStr = objectToQueryParams(post);
    //将Value值放到jsonData中 到时根据keyType是否为多选框再处理Value值
    // keyType为select 直接给数组赋值，若为multiSelect 则取list值
    const selectedList =
      (queryParams.list.length &&
        queryParams.list.map((item) => {
          return {
            value: item,
          };
        })) ||
      [];
    const jsonData = queryParams.list.length
      ? selectedList
      : [{ value: queryParams.value }];
    const result = (await BasicApi.Query({ inputStr, jsonData })) as any;
    const { code, msg, data, rsCount } = result;
    if (code !== 200) {
      message.error(msg);
      return;
    }
    // message.success(msg)
    total.value = rsCount;
    if (rsCount == 0) {
      list.value = [];
      column.value = [];
      operList.value = [];
      return;
    }
    //格式化数据
    const { listInfo, col } = formatTableCol(data);
    list.value = listInfo || [];
    column.value = col || [];

    //格式化操作按钮
    const selectArr =
      data.operInfo &&
      data.operInfo.filter((item: any) => item.Value == "Select");
    selectShow.value =
      selectArr && selectArr.length && selectArr[0].IsShow == "true"
        ? true
        : false;
  } finally {
    loading.value = false;
  }
};

const emit = defineEmits(["selection-change"]);
/** 多选操作 */
const handleSelectionChange = (val: any) => {
  val.length && emit("selection-change", val, headList.value);
};

const modalRef = ref();
/** 编辑弹框 */
const handleEdit = (data: any) => {
  modalRef.value.open(queryParams, data);
};

const handleDetail = (data: any, label: string, value: string) => {
  console.log(label, "label");
  //打开父组件的详情Tab
  eventBus.emit("addDetailTab", { data, label, value });
  setTimeout(() => {
    //并通知详情页渲染
    eventBus.emit("getDetailField", props.tableInfo);
    eventBus.emit("getDetailList", data);
  }, 0);
};
/** 明细弹框 */
const breakdownRef = ref();
const handleBreakdown = (data: any) => {
  breakdownRef.value.open(queryParams, data);
};

/** 删除按钮操作 */
const handleDelete = async (data: any) => {
  try {
    // 删除的二次确认
    await message.delConfirm();
    // 发起删除
    const inputStr = objectToQueryParams({
      groupName: queryParams.groupName,
      jobType: queryParams.jobType,
      operType: "Delete",
    });
    const jsonData = data;
    const result = (await BasicApi.Operate({ inputStr, jsonData })) as any;
    const { code, msg } = result;
    if (code !== 200) {
      message.error(msg);
      return;
    }
    message.success(msg);
    // 刷新列表
    await getList();
  } catch {}
};

// 创建 ref 来引用容器元素
const boxRef = ref();
// 标记容器宽度是否发生变化
const isWidthChanged = ref(false);

const getBoxWidth = () => {
  return boxRef.value?.offsetWidth;
};

// 创建 ResizeObserver 实例
let resizeObserver: any;
onMounted(() => {
  // 创建 ResizeObserver 实例，传入回调函数
  resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      // 这里可以编写具体要执行的操作，例如更新状态、发送请求等
      // 这里简单地将 isWidthChanged 设置为 true 表示宽度已变化
      isWidthChanged.value = true;
      console.log("容器宽度变化为:", entry.contentRect.width);
      if (entry.contentRect.width) {
        // 可以在这里添加更多操作，比如调用某个函数
        performSpecificOperation(entry.contentRect.width);
      }
    }
  });

  // 开始监听容器元素的尺寸变化
  if (boxRef.value) {
    resizeObserver.observe(boxRef.value);
  }
});

onUnmounted(() => {
  // 当组件卸载时，停止监听并清理资源
  if (resizeObserver && boxRef.value) {
    resizeObserver.unobserve(boxRef.value);
  }
});

// 定义一个具体的操作函数
const performSpecificOperation = (newWidth: any) => {
  console.log("执行了特定操作，新宽度为:", newWidth);
  render(newWidth);
  // 这里可以添加更多复杂的操作，如更新数据、调用 API 等
};

const render = (contentWidth?: number) => {
  const result = props.tableInfo;
  let resultWidth = contentWidth ? contentWidth : getBoxWidth();
  //渲染表头
  if (result?.fieldInfo?.length) {
    column.value = JSON.parse(JSON.stringify(result.fieldInfo));
    // //含有selection则宽度 - 50
    if (selectShow.value) {
      resultWidth = resultWidth - 50;
    }
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = column.value.reduce(
      (first, cur) => first + cur.width,
      0
    );
    if (sumPercent > 100) {
      column.value = getColWidth(column.value, resultWidth);
    } else {
      column.value = getColWidth(column.value, resultWidth);
      setLastWidth(column.value, resultWidth);
    }
  }
  //行操作
  const len = result?.pageInfo?.lineOperate.length;
  if (list.value.length && len) {
    resultWidth = len && resultWidth - 120;
    const temp = JSON.parse(JSON.stringify(result.fieldInfo));
    //当宽度之和等于百分比的时候 最后一列需要处理 解决小空隙问题
    const sumPercent = temp.reduce(
      (first: any, cur: any) => first + cur.width,
      0
    );
    if (sumPercent > 100) {
      column.value = getColWidth(temp, resultWidth);
    } else {
      column.value = getColWidth(temp, resultWidth);
      setLastWidth(column.value, resultWidth);
    }
    operList.value = result?.pageInfo?.lineOperate || [];
  }
};

watchEffect(() => {
  render();
});

const refreshList = (width: number) => {
  render(width);
};
eventBus.on("refreshList", refreshList);
</script>
<template>
  <div ref="boxRef" class="table-box">
    <el-table
      v-loading="loading"
      :data="list"
      style="width: 100%"
      height="730px"
      highlight-current-row
      :header-cell-style="{ background: '#143452' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="selectShow"
        align="center"
        type="selection"
        width="50"
      />
      <template v-for="item in column" :key="item.value">
        <el-table-column
          v-if="item.isShow == 'true'"
          align="center"
          :prop="item.value"
          :label="item.label"
          :width="item.width"
          show-overflow-tooltip
        >
          <template #default="scope">
            <template v-if="item.isEdit == 'false' && isDate(item.value)">
              <span>{{ formatDate(scope.row[item.value]) }}</span>
            </template>
            <template v-else>
              <!-- 处理下拉框或者输入框 -->
              <template v-if="item.isEdit == 'true'">
                <el-select
                  v-if="item.type == 'select'"
                  v-model="scope.row[item.value]"
                  filterable
                  clearable
                  placeholder="请选择"
                  style="width: 90%"
                >
                  <el-option
                    v-for="_ in item.cmbInfo"
                    :key="_.value"
                    :label="_.label"
                    :value="_.value"
                  />
                </el-select>
                <el-input
                  v-else-if="item.type == 'number'"
                  type="number"
                  v-model="scope.row[item.value]"
                  placeholder="请输入"
                  style="width: 90%"
                />
                <el-date-picker
                  v-else-if="item.type == 'date'"
                  type="date"
                  v-model="scope.row[item.value]"
                  placeholder="请选择"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 90%"
                />
                <el-input
                  v-else
                  type="text"
                  v-model="scope.row[item.value]"
                  placeholder="请输入"
                  style="width: 90%"
                />
              </template>
              <template v-else>
                <span>{{ scope.row[item.value] }}</span>
              </template>
            </template>
          </template>
        </el-table-column>
      </template>

      <el-table-column
        v-if="operList.length"
        fixed="right"
        label="操作"
        align="center"
        width="120"
      >
        <template #default="scope">
          <template v-for="(item, index) in operList" :key="index">
            <el-button
              class="my-btn"
              v-if="item.value == 'Edit'"
              link
              type="primary"
              @click="handleEdit(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              class="my-btn"
              v-if="item.value == 'WorkFlow'"
              link
              type="warning"
              @click="handleDetail(list[scope.$index], item.label, item.value)"
            >
              {{ item.label }}
            </el-button>
            <el-button
              class="my-btn"
              v-if="item.value == 'Delete'"
              link
              type="danger"
              @click="handleDelete(list[scope.$index])"
            >
              {{ item.label }}
            </el-button>
            <el-button
              class="my-btn"
              v-if="item.value == 'Breakdown'"
              link
              type="success"
              @click="handleBreakdown(list[scope.$index])"
            >
              {{ item.Label }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 编辑弹框 -->
  <EditModal ref="modalRef" @refresh="getList" />
  <!-- 明细弹框 -->
  <BreakdownModal ref="breakdownRef" />
  <!-- 表单弹窗：只读详情 -->
  <!-- <DetailModal ref="detailRef" /> -->
</template>
<style lang="less" scoped>
.table-box {
  :deep(.el-table) {
    font-size: 14px;
    background-color: #141c36;
  }
  :deep(.el-table .cell) {
    font-size: 16px;
  }

  :deep(.el-table__empty-block) {
    background-color: #141c36;
  }

  :deep(.el-table th.el-table__cell) {
    background-color: #143452;
    color: #79a0c9;
    font-weight: 600;
  }

  :deep(.el-table .el-table__cell) {
    background: #141c36;
    color: #799ac1;
    border-bottom: 0;
    padding: 0.5rem 0;
  }

  :deep(
      .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell
    ) {
    background-color: #1f4465;
  }

  :deep(
      .el-table__body tr.hover-row.current-row > td.el-table__cell,
      .el-table__body
        tr.hover-row.el-table__row--striped.current-row
        > td.el-table__cell,
      .el-table__body tr.hover-row.el-table__row--striped > td.el-table__cell,
      .el-table__body tr.hover-row > td.el-table__cell
    ) {
    background-color: #143452;
  }

  :deep(.el-input__wrapper) {
    background: #1c324f;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    color: #799ac1;
    height: 2.6rem;
    color: #799ac1;
    font-size: 1.3rem;
  }

  :deep(.el-table) {
    --el-table-bg-color: none;
  }

  :deep(.el-table tbody .el-table__cell) {
    height: 20px;
    padding: 7px 0;
  }
  :deep(.el-input.is-disabled .el-input__wrapper) {
    background: #1c324f;
    box-shadow: none;
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    -webkit-text-fill-color: #799ac1;
  }
  :deep(.el-table__inner-wrapper::before) {
    display: none;
  }
  .my-btn {
    font-size: 16px;
    height: 28px;
  }
}
</style>
